#pragma once

#include <iostream>
#include "Reactor.hpp"
#include "Connection.hpp"
#include "Socket.hpp"
#include "Channel.hpp"
using namespace MySocket;
class Listener : public Connection
{
public:
    Listener(int port = defaultport):_port(port),_listensockfd(std::make_unique<TcpSocket>())
    {
        //创建套接字
        _listensockfd->BuildSocket(_port);
        SetNonBlock(_listensockfd->Fd());
        SetEvent(EPOLLIN|EPOLLET);
    }

    void Recver() override
    {
        InetAddr client;

        while(true)
        {
            int sockfd = _listensockfd->Accept(&client);

            if(sockfd == ACCEPT_DONE)
                break;
            else if(sockfd == ACCEPT_ERROR)
                break;
            else if(sockfd == ACCEPT_CONTINUE)
                continue;
            else
            {
                //创建普通套接字，交给Reaction管理
                std::shared_ptr<Connection> Con = std::make_shared<Channel>(sockfd,client);
                Con->SetEvent(EPOLLIN|EPOLLET);
                if(_handler != nullptr)
                    Con->RegisterHandler(_handler);
                GetOwner()->AddConnection(Con);
            }
        }
    }
    void Sender() override
    {}
    void Expecter() override
    {}
    int GetSockfd() override
    {
        return _listensockfd->Fd();
    }
    ~Listener()
    {}
private:
    int _port;
    std::unique_ptr<TcpSocket> _listensockfd;
};